package com.xmut.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xmut.mall.product.constant.ProductConstant;
import com.xmut.mall.product.dao.AttrDao;
import com.xmut.mall.product.entity.*;
import com.xmut.mall.product.feign.CouponFeignService;
import com.xmut.mall.product.feign.SearchFeignService;
import com.xmut.mall.product.feign.WareFeignService;
import com.xmut.mall.product.searchparam.ManagerProductSearchParam;
import com.xmut.mall.product.searchparam.ProductReviewSearchParam;
import com.xmut.mall.product.searchparam.SpuSearchParam;
import com.xmut.mall.product.service.*;
import com.xmut.mall.product.to.es.ProductESTo;
import com.xmut.mall.product.utils.*;
import com.xmut.mall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xmut.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService imagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private SkuDescService skuDescService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public RespBean testJwt() {
        String token = request.getHeader("Authorization");
        String userInfo = JWTUtils.getClaim(token);
        return RespBean.success("成功", token + " " + userInfo);
    }

    // 这种场景最适合使用seata的at模式
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1.保存spu基本信息
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        // 2.保存spu的描述图片
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        // 3.保存spu的图片集
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(), images);
        // 4.保存spu的规格参数
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        // 5.保存spu的积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败:");
        }


        // 5.保存当前spu对应的所有sku的信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.stream().forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                // 5.1 sku的基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 返回的结果如果是true就会被收集，如果是false就会被过滤掉
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                // 5.2 sku的图片信息
                skuImagesService.saveBatch(imagesEntities);
                // TODO 没有路径的图片无需保存

                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                // 5.3 sku的销售属性信息
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                // 5.4 sku的优惠、满减信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程调用保存sku优惠满减信息失败");
                    }
                }

            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public void productUp(Long spuId) {

        //查出该spu对应的所有sku
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);

        // 将该spu所有的sku的id封装为list
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //  4.查询当前sku所有可以被检索的规格属性，
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
        // 将查到的该spu的attr的id封装为list
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        // 查询我们的到的attrid中可以用于检索(search_type = 1)的attr的id
        List<Long> searchAttrIds = attrService.selectSearchAttrsIds(attrIds);

        // 用于下面的fliter进行过滤
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<ProductESTo.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            //过滤出能用于检索的attr
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            // 将这些可用于检索的attr使用map映射成传给缓存服务所用的attr中
            ProductESTo.Attrs attr1 = new ProductESTo.Attrs();
            BeanUtils.copyProperties(item, attr1);
            return attr1;
        }).collect(Collectors.toList());

        // 查询库存系统 看看该商品是否还有库存
        Map<Long, Boolean> stockMap = null;

        try {
            R r = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询出现异常：原因{}", e);
        }

        // 封装每个Sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<ProductESTo> upProducts = skus.stream().map(sku -> {
            // 组装ESto信息
            ProductESTo esTo = new ProductESTo();
            BeanUtils.copyProperties(sku, esTo);

            esTo.setSkuPrice(sku.getPrice());
            esTo.setSkuImg(sku.getSkuDefaultImg());

            // 设置库存信息
            if (finalStockMap == null) {
                esTo.setHasStock(true);
            } else {
                esTo.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            // 热度评分 默认给0
            esTo.setHotScore(0L);

            // 查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esTo.getBrandId());
            esTo.setBrandName(brand.getName());
            esTo.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esTo.getCatalogId());
            esTo.setCatalogName(category.getName());

            // 设置可检索熟悉（注意这里都是可以进行检索的attr）
            esTo.setAttrs(attrsList);

            return esTo;
        }).collect(Collectors.toList());

        // 将封装好的数据发送给ES服务进行保存
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // 如果保存成功就修改当前spu的状态为上架
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }

    }

    /**
     * 根据spuId获取spu信息
     *
     * @param spuId
     * @return
     */
//    @Cacheable(value = "spuInfo", key = "#root.methodName+#root.args[0]")
    @Override
    public SpuInfoEntity getSpuInfoBySpuId(Long spuId) {
        return this.baseMapper.selectById(spuId);
    }

    /**
     * 保存商品Spu
     *
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean saveSpu(ProductSpuSaveVo vo) {
        // 首先保存spuinfo
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        Long spuId = IdWorker.getId();
        spuInfoEntity.setId(spuId);
        spuInfoEntity.setBrandId(vo.getBrandId());
        spuInfoEntity.setCatalogId(vo.getCatalogId());
        spuInfoEntity.setSpuName(vo.getSpuName());
        spuInfoEntity.setSpuDescription(vo.getSpuDescription());
        spuInfoEntity.setWeight(vo.getWeight());
        spuInfoEntity.setPublishStatus(vo.getPublishStatus());
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setReviewStatus(2);
        spuInfoEntity.setStoreName(vo.getStoreName());
        spuInfoEntity.setStoreId(vo.getStoreId());

        // 保存spu的描述信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(vo.getDecript());

        // 保存spuImages
        SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
        spuImagesEntity.setSpuId(spuId);
        spuImagesEntity.setImgUrl(vo.getImages());

        // 保存商品的attrValue
        List<ProductAttrValueEntity> productAttrValueList = new ArrayList<>();
        for (BaseAttrs baseAttr : vo.getBaseAttrs()) {
            if (baseAttr!=null){
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuId);
                productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                productAttrValueEntity.setAttrName(baseAttr.getAttrName());
                productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                productAttrValueList.add(productAttrValueEntity);
            }
        }

        // 保存其中的sku
        List<ProductSpuSaveSkusVo> skus = vo.getSkus();
        // 准备几个list 在循环里面收集数据 最后一起保存到数据库
        List<SkuInfoEntity> skuInfoList = new ArrayList<>();
        List<SkuImagesEntity> skuImageList = new ArrayList<>();
        List<SkuDescEntity> skuDescList = new ArrayList<>();
        List<SkuSaleAttrValueEntity> skuSaleAttrList = new ArrayList<>();
        List<WareSkuVo> wareSkuVoList = new ArrayList<>();
        // 遍历skus 把里面的东西拆除来变成list 然后使用savebatch保存
        for (ProductSpuSaveSkusVo skuVo : skus) {
            // 先保存sku的info表
            Long skuId = IdWorker.getId();
            SkuInfoEntity skuInfo = new SkuInfoEntity();
            skuInfo.setSkuId(skuId);
            skuInfo.setSpuId(spuId);
            skuInfo.setSkuName(skuVo.getSkuName());
            skuInfo.setCatalogId(vo.getCatalogId());
            skuInfo.setBrandId(vo.getBrandId());
            skuInfo.setSkuDefaultImg(skuVo.getSkuImages().get(0).getImgUrl());
            skuInfo.setSkuTitle(skuVo.getSkuTitle());
            skuInfo.setSkuSubtitle(skuVo.getSkuSubtitle());
            skuInfo.setPrice(skuVo.getPrice());
            skuInfo.setSaleCount(0L);
            skuInfo.setStoreId(vo.getStoreId());
            skuInfoList.add(skuInfo);

            // 保存库存
            WareSkuVo wareSkuVo = new WareSkuVo();
            wareSkuVo.setStock(skuVo.getStock());
            wareSkuVo.setSkuId(skuId);
            wareSkuVo.setSpuId(spuId);
            wareSkuVo.setStockLocked(0);
            wareSkuVo.setSkuName(skuVo.getSkuName());
            wareSkuVoList.add(wareSkuVo);

            // 保存skuimage表
            for (Images skuImage : skuVo.getSkuImages()) {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(skuImage.getImgUrl());
                skuImagesEntity.setDefaultImg(0);
                skuImageList.add(skuImagesEntity);
            }



            // 保存sku详情描述
            SkuDescEntity skuDescEntity = new SkuDescEntity();
            skuDescEntity.setSkuId(skuId);
            skuDescEntity.setSkuDesc(skuVo.getSkuIntroImage().get(0).getImgUrl());
            skuDescList.add(skuDescEntity);


            // 保存skusaleattr表 保存sku的销售属性表
            for (Attr attr : skuVo.getAttr()) {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setSkuId(skuId);
                skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                skuSaleAttrList.add(skuSaleAttrValueEntity);
            }
        }
        // 保存 spu相关
        Boolean spuInfoSaveResult = this.save(spuInfoEntity);

        Boolean spuInfoDescSaveResult = spuInfoDescService.save(spuInfoDescEntity);

        Boolean spuImageSaveResult = spuImagesService.save(spuImagesEntity);

        // 保存sku相关
        Boolean skuInfoSaveResult = skuInfoService.saveBatch(skuInfoList);

        Boolean skuImageSaveResult = skuImagesService.saveBatch(skuImageList);

        Boolean skuDescSaveResult = skuDescService.saveBatch(skuDescList);

        Boolean skuSaleAttrValueSaveResult = skuSaleAttrValueService.saveBatch(skuSaleAttrList);

        Boolean productAttrValueSaveResult = productAttrValueService.saveBatch(productAttrValueList);

        RespBean generateSkuWareRespBean = wareFeignService.generateSkuWare(wareSkuVoList);
        Boolean wareSkuSaveResult = false;
        if (generateSkuWareRespBean.getCode() == 201){
            wareSkuSaveResult = true;
        }else {
            try {
                throw new Exception("sku库存创建失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (spuInfoSaveResult && spuInfoDescSaveResult && spuImageSaveResult && skuInfoSaveResult && skuImageSaveResult &&
                skuDescSaveResult && skuSaleAttrValueSaveResult && productAttrValueSaveResult && wareSkuSaveResult) {
            return RespBean.success("保存成功");
        } else {
            return RespBean.success("网络延迟，请稍后重试");
        }
    }

    /**
     * 获取商品审核分页数据
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getProductReviewByPage(PageVO vo, ProductReviewSearchParam param) {
        IPage<ProductReviewVo> page = this.baseMapper.getProductReviewByPage(PageUtil.initPage(vo),param);
        return RespBean.success("获取成功",page);
    }

    /**
     * 审核Spu
     * @param vo
     * @return
     */
    @Override
    public RespBean authSpu(AuthSpuVo vo) {
        Boolean update = this.update(new UpdateWrapper<SpuInfoEntity>().set("review_status", vo.getAuthStatus())
                .eq("id", vo.getSpuId()));

        if (update){
            return RespBean.success("操作成功");
        }else {
            return RespBean.error("操作失败");
        }
    }

    /**
     * 获取spu的详情信息
     * @param id
     * @return
     */
    @Override
    public RespBean getSpuDetail(Long id) {
        SpuDetailVo vo = new SpuDetailVo();
        SpuInfoEntity spuInfo = this.getById(id);

        vo.setSpuName(spuInfo.getSpuName());
        vo.setSpuDescription(spuInfo.getSpuDescription());
        vo.setSpuStoreName(spuInfo.getStoreName());

        // 组装分类树
        List<CategoryEntity> cateList = categoryService.getCateParentAndMerge(spuInfo.getCatalogId());
        StringBuilder stringBuilder = new StringBuilder();
        for (CategoryEntity category : cateList) {
            stringBuilder.append(category.getName()+"/");
        }
        vo.setSpuCate(stringBuilder.toString());

        // 查询品牌
        BrandEntity brand = brandService.getById(spuInfo.getBrandId());
        vo.setSpuBrand(brand.getName());

        // 查询当前spu的属性
        List<ProductAttrValueEntity> attrList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", id));
        vo.setSpuAttr(attrList);

        // 查询sku
        List<SkuInfoEntity> skus = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", id));

        List<SpuDetailShowSkuInfoVo> skuVos = skus.stream().map(item -> {
            SpuDetailShowSkuInfoVo skuVo = new SpuDetailShowSkuInfoVo();
            skuVo.setSkuId(item.getSkuId());
            skuVo.setSkuName(item.getSkuName());
            skuVo.setSkuPrice(item.getPrice());
            // 获取图片
            List<SkuImagesEntity> skuImgList = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", item.getSkuId()));
            skuVo.setSkuImg(skuImgList.get(0).getImgUrl());
            return skuVo;
        }).collect(Collectors.toList());

        vo.setSkus(skuVos);

        // 查询详情大图
        SpuInfoDescEntity spuDesc = spuInfoDescService.getOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", id));
        vo.setIntroImg(spuDesc.getDecript());

        return RespBean.success("获取成功",vo);


    }

    /**
     * 获取spu的分页信息
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getSpuByPage(PageVO vo, SpuSearchParam param) {
        IPage<SpuPageVo> page = this.baseMapper.getSpuByPage(PageUtil.initPage(vo),param);

        return RespBean.success("获取成功",page);
    }

    /**
     * 商家端点击编辑获取Spu的全部信息Z
     * @param spuId
     * @return
     */
    @Override
    public RespBean getSpuDetailWithEdit(Long spuId) {
        ProductSpuSaveVo vo = new ProductSpuSaveVo();
        // 查询baseattr
        List<ProductAttrValueEntity> attrValues = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<BaseAttrs> baseAttrs = attrValues.stream().map(item -> {
            BaseAttrs attr = new BaseAttrs();
            attr.setAttrId(item.getAttrId());
            attr.setAttrName(item.getAttrName());
            attr.setAttrValues(item.getAttrValue());
            return attr;
        }).collect(Collectors.toList());
        vo.setBaseAttrs(baseAttrs);

        //设置spu的基本信息
        SpuInfoEntity spuInfo = this.getById(spuId);
        vo.setStoreId(spuInfo.getStoreId());
        vo.setStoreName(spuInfo.getStoreName());
        vo.setSpuName(spuInfo.getSpuName());
        vo.setSpuDescription(spuInfo.getSpuDescription());
        vo.setPublishStatus(spuInfo.getPublishStatus());
        vo.setWeight(spuInfo.getWeight());
        vo.setBrandId(spuInfo.getBrandId());
        vo.setCatalogId(spuInfo.getCatalogId());

        // 设置Bounds
        Bounds bounds = new Bounds();
        bounds.setBuyBounds(new BigDecimal(1));
        bounds.setGrowBounds(new BigDecimal(1));
        vo.setBounds(bounds);

        // 查询spu图片
        SpuImagesEntity spuImage = spuImagesService.getOne(new QueryWrapper<SpuImagesEntity>().eq("spu_id", spuId));
        vo.setImages(spuImage.getImgUrl());
        // 查询Spu详细大图
        SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", spuId));
        vo.setDecript(spuInfoDesc.getDecript());

        // 查询Spu对应的Sku信息
        List<SkuInfoEntity> skuInfoList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<ProductSpuSaveSkusVo> skus = skuInfoList.stream().map(skuInfo -> {
            ProductSpuSaveSkusVo skuVo = new ProductSpuSaveSkusVo();
            skuVo.setSkuName(skuInfo.getSkuName());
            skuVo.setSkuTitle(skuInfo.getSkuTitle());
            skuVo.setSkuSubtitle(skuInfo.getSkuSubtitle());
            skuVo.setPrice(skuInfo.getPrice());
            skuVo.setSkuId(skuInfo.getSkuId());

            // 获取sku展示图片
            List<SkuImagesEntity> skuImage = skuImagesService.list(new QueryWrapper<SkuImagesEntity>()
                    .eq("sku_id", skuInfo.getSkuId()));
            List<Images> skuImages = skuImage.stream().map(image -> {
                Images img = new Images();
                img.setImgUrl(image.getImgUrl());
                img.setDefaultImg(0);
                return img;
            }).collect(Collectors.toList());
            skuVo.setSkuImages(skuImages);

            // 获取sku的详情大图
            SkuDescEntity skuDescEntity = skuDescService.getOne(new QueryWrapper<SkuDescEntity>().eq("sku_id", skuInfo.getSkuId()));
            List<Images> skuIntroList = new ArrayList<>();
            Images introImages = new Images();
            introImages.setDefaultImg(0);
            introImages.setImgUrl(skuDescEntity.getSkuDesc());
            skuIntroList.add(introImages);
            skuVo.setSkuIntroImage(skuIntroList);

            // 获取skuVo的SaleAttr
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = skuSaleAttrValueService.list(new QueryWrapper<SkuSaleAttrValueEntity>()
                    .eq("sku_id", skuInfo.getSkuId()));
            List<Attr> saleAttrList = skuSaleAttrValueEntityList.stream().map(attr -> {
                Attr saleAttr = new Attr();
                saleAttr.setAttrId(attr.getAttrId());
                saleAttr.setAttrName(attr.getAttrName());
                saleAttr.setAttrValue(attr.getAttrValue());
                return saleAttr;
            }).collect(Collectors.toList());
            skuVo.setAttr(saleAttrList);

            return skuVo;
        }).collect(Collectors.toList());
        vo.setSkus(skus);


        return RespBean.success("获取成功",vo);

    }

    /**
     * 获取spu对应的sku商品的库存信息
     * @param spuId
     * @return
     */
    @Override
    public RespBean getSpuStock(Long spuId) {
        // 查出所有的sku的信息
        List<SkuInfoEntity> skuInfo = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        // 查出所有的Sku的库存
        RespBean skuWareRespBean = wareFeignService.getSkuWare(spuId);

        List<WareSkuVo> wareSkuVoList = JSON.parseObject(JSON.toJSONString(skuWareRespBean.getObj()), new TypeReference<List<WareSkuVo>>() {
        });

        List<SkuStockVo> result = skuInfo.stream().map(item -> {
            SkuStockVo vo = new SkuStockVo();
            vo.setSkuId(item.getSkuId());
            vo.setSkuName(item.getSkuName());
            vo.setSkuImg(item.getSkuDefaultImg());
            List<WareSkuVo> wareSkuVos = wareSkuVoList.stream().filter(i -> i.getSkuId().equals(item.getSkuId())).collect(Collectors.toList());
            vo.setSkuStock(wareSkuVos.get(0).getStock());
            return vo;
        }).collect(Collectors.toList());


        return RespBean.success("获取成功",result);
    }

    /**
     * 商品spu上架
     * @param spuId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean productSpuUp(Long spuId) {
        // 首先获取当前spu进行前置判断
        SpuInfoEntity spuInfo = this.getById(spuId);
        if (spuInfo.getReviewStatus() == 0){
            return RespBean.error("该商品并未通过审核");
        }
        if (spuInfo.getReviewStatus() == 2){
            return RespBean.error("该商品正在审核中");
        }
        if (spuInfo.getPublishStatus() == 1){
            return RespBean.error("该商品已上架");
        }
        //查出该spu对应的所有sku
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        BrandEntity brandEntity = brandService.getById(skus.get(0).getBrandId());
        CategoryEntity categoryEntity = categoryService.getById(skus.get(0).getCatalogId());
        // 组装attrList
        // 查找出属于本spu的search_type为1(可进行检索)的attr
        List<ProductAttrValueEntity> productAttrValueList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>()
                .eq("spu_id", spuId).eq("search_type", 1));
        // 收集ID
//        List<Long> attrIds = productAttrValueList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
//        List<AttrEntity> attrEntityList = attrDao.selectBatchIds(attrIds);
        List<ProductESTo.Attrs> attrsList = productAttrValueList.stream().map(item -> {
            ProductESTo.Attrs attrs = new ProductESTo.Attrs();
            attrs.setAttrId(item.getAttrId());
            attrs.setAttrName(item.getAttrName());
            attrs.setAttrValue(item.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());

        RespBean spuStock = wareFeignService.getSpuStock(spuId);
        Map<Long, Boolean> stockMap = JSON.parseObject(JSON.toJSONString(spuStock.getObj()), new TypeReference<Map<Long, Boolean>>() {
        });

        List<ProductESTo> esTo = skus.stream().map(item -> {
            ProductESTo to = new ProductESTo();
            to.setSkuId(item.getSkuId());
            to.setSpuId(spuId);
            to.setSkuTitle(item.getSkuTitle());
            to.setSkuPrice(item.getPrice());
            to.setSkuImg(item.getSkuDefaultImg());
            to.setSaleCount(item.getSaleCount());
            // 设置库存
            to.setHasStock(stockMap.get(item.getSkuId()));
            to.setHotScore(0L);
            to.setBrandId(item.getBrandId());
            to.setBrandName(brandEntity.getName());
            to.setBrandImg(brandEntity.getLogo());
            to.setCatalogId(item.getCatalogId());
            to.setCatalogName(categoryEntity.getName());
            to.setStoreId(item.getStoreId());
            to.setStoreName(item.getStoreName());
            to.setAttrs(attrsList);
            return to;
        }).collect(Collectors.toList());

        // 调用搜索服务进行保存
        R r = searchFeignService.productStatusUp(esTo);
        System.out.println("保存结果:"+r);
        if (r.getCode() == 0){
            // 如果保存成功 就修改该spu的上架状态改为上架
            boolean update = this.update(new UpdateWrapper<SpuInfoEntity>().set("publish_status", 1).eq("id", spuId));
            if (update){
                return RespBean.success("保存成功");
            }else {
                return RespBean.error("保存失败");
            }
        }else {
            return RespBean.error("保存失败");
        }
    }

    /**
     * 商品下架
     * @param spuId
     * @return
     */
    @Override
    public RespBean productOFF(Long spuId) {
        // 先判断当前spu的状态
        SpuInfoEntity spuInfo = this.getById(spuId);
        if (spuInfo.getReviewStatus() == 0){
            return RespBean.error("该商品并未通过审核");
        }
        if (spuInfo.getReviewStatus() == 2){
            return RespBean.error("该商品正在审核中");
        }
        if (spuInfo.getPublishStatus() == 0){
            return RespBean.error("该商品已下架");
        }

        // 查询该spu对应的sku
        List<SkuInfoEntity> skuList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIds = skuList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 把Id传过去然后删掉ES的缓存
        R r = searchFeignService.productOFF(skuIds);
        if (r.getCode() == 0){
            // 下架成功
            boolean update = this.update(new UpdateWrapper<SpuInfoEntity>().set("publish_status", 0).eq("id", spuId));
            if (update){
                return RespBean.success("下架成功");
            }else {
                return RespBean.error("下架失败");
            }
        }else {
            return RespBean.error("下架失败");
        }
    }

    /**
     * 获取官方管理端的Spu分页数据
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getManagerSpuPage(PageVO vo, ManagerProductSearchParam param) {
        IPage<ManagerProductPageVo> page = this.baseMapper.getManagerSpuPage(PageUtil.initPage(vo),param);

        return RespBean.success("获取成功",page);
    }


}